<?php

/**
 * 后台 Tags 模块 Model
 * ============================================================================
 * TBlog TBlog博客系统　BY Tmac PHP MVC framework
 * $Author: zwt007 $  <zwttmac@qq.com>
 * $Id: tags.class.php 107 2012-03-14 11:40:18Z zwt007 $
 * http://www.t-mac.org；
 */
class tags extends Model
{

    private $db;
    private $tags_table;
    private $tags_info_table;
    private $article_table;

    /**
     * 初始化变量　定义私有变量
     */
    public function _init()
    {
        //连接数据库
        $this->db = $this->connect();
        $this->tags_table = DB_PREFIX . 'tags';
        $this->tags_info_table = DB_PREFIX . 'tags_info';
        $this->article_table = DB_PREFIX . 'article';
    }

    /**
     * 保存
     * @param string $menusMain
     * return Boole
     */
    public function addTags($info, $mode = 'INSERT', $where = '')
    {
        $rs = $this->db->autoExecute($this->tags_table, $info, $mode, $where);
        return $rs;
    }

    /**
     * 保存返回article_id
     * @param string $menusMain
     * return Boole
     */
    public function addTagsReturn($info)
    {
        $rs = $this->db->autoInsertReturn($this->tags_table, $info);
        return $rs;
    }

    /**
     * 保存
     * @param string $menusMain
     * return Boole
     */
    public function addTagsInfo($info, $mode = 'INSERT', $where = '')
    {
        $rs = $this->db->autoExecute($this->tags_info_table, $info, $mode, $where);
        return $rs;
    }

    /**
     * 获取一个资讯栏目信息
     * @param int $class_id 栏目id
     * return array
     */
    public function getTagsInfo($id)
    {
        $rs = $this->db->getRow("SELECT * FROM $this->tags_table WHERE tag_id = '$id' LIMIT 0,1");
        return $rs;
    }

    /**
     * 取Tags信息 从Tag_name中取
     * @param type $tag_name
     * @return type 
     */
    public function getTagsInfoByName($tag_name)
    {
        $rs = $this->db->getRow("SELECT tag_id,tag_name FROM $this->tags_table WHERE tag_name = '$tag_name' LIMIT 0,1");
        return $rs;
    }

    /**
     * 获取所有资讯
     * return article_class,pages
     */
    public function getTagsList($search_keyword = null, $url = null)
    {
        $where = " WHERE 1=1";
        if ($url == '')
            $url = PHP_SELF . '?m=tags';

        if ($search_keyword != '') {
            $where .= " AND tag_name LIKE '%" . $search_keyword . "%'";
            $url .= "&search_keyword=$search_keyword";
        }

        $url .= '&page=';
        $count = $this->db->getOne("SELECT COUNT(*) FROM $this->tags_table {$where}");
        $pages = $this->P('Pages');
        $pages->setTotal($count);
        $pages->setUrl($url);
        $pages->setPrepage(20);
        $limit = $pages->getSqlLimit();
        $sql = "SELECT * FROM {$this->tags_table}{$where} ORDER BY tag_id DESC LIMIT $limit";
        $rs = $this->db->getAll($sql);

//把文章的当前page写到cookies里
        HttpResponse::setCookie('tags_page', $pages->getNowPage());

        $ErrorMsg = '';
        if ($count == 0) {
            $ErrorMsg = "暂无Tags!";
        }
        $result = array('rs' => $rs, 'pageCurrent' => $pages->getNowPage(), 'page' => $pages->show(), 'ErrorMsg' => $ErrorMsg);
        return $result;
    }

    /**
     * 判断Tags唯一
     * @param type $id
     * @param type $name
     * @return type 
     */
    public function checkTags($id, $name)
    {
        $tag_info = $this->getTagsInfo($id);
        if ($tag_info['tag_name'] == $name) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * del
     * @param int $class_id
     */
    public function delTags($id)
    {
        $rs = $this->db->execute("DELETE FROM $this->tags_table WHERE tag_id in ($id)");
        return $rs;
    }

    /**
     * del
     * @param int $class_id
     */
    public function delTagsInfo($id)
    {
        $rs = $this->db->execute("DELETE FROM $this->tags_info_table WHERE tag_id in ($id)");
        return $rs;
    }

    /**
     * 取所有的Tags
     * @return type 
     */
    public function getTagsArray()
    {
        $sql = "SELECT * FROM $this->tags_table ORDER BY tag_id DESC";
        $rs = $this->db->getAll($sql);
        return $rs;
    }

    /**
     * 取文章 的所有Tags_info
     * @param type $article_id
     * @return type 
     */
    public function getTagsInfoArrayByArticle_id($article_id)
    {
        $sql = "SELECT * FROM $this->tags_info_table WHERE article_id = '$article_id'";
        $rs = $this->db->getAll($sql);
        return $rs;
    }

    /**
     * 存Tag_info相关
     * @param type $article_id
     * @param array $tag_id_array
     * @param type $tag_name_array
     * @return type 
     */
    public function saveTagsInfo($article_id, $tag_id_array = array(), $tag_name_array = array())
    {
        if (is_array($tag_id_array)) {
            foreach ($tag_id_array AS $k => $v) {
                $tag_array[$v] = $tag_name_array[$k];
            }
            $tag_id_string = implode(',', $tag_id_array);
        } else {
            $tag_id_array = array();
            $tag_id_string = '';
        }

        $rs = $this->getTagsInfoArrayByArticle_id($article_id);

        //初始化老的tag_id
        $tag_id_old_array = array();
        if ($rs) {
            foreach ($rs AS $kk => $vv) {
                $tag_id_old_array[] = $vv['tag_id'];
            }
        }

        //进行对比 取差值 进行insert
        $tag_id_insert_array = array_diff($tag_id_array, $tag_id_old_array);
        if ($tag_id_insert_array) {
            $sql = "INSERT INTO $this->tags_info_table (tag_id, article_id, tag_name) VALUES ";
            $sql_values = '';
            foreach ($tag_id_insert_array AS $kkk => $vvv) {
                $sql_values .= ",('$vvv', '$article_id', '$tag_array[$vvv]')";
                //tag表里的tag_num总数记录增加一
                $tag_num_update_sql = "UPDATE $this->tags_table SET tag_usernum = tag_usernum+1 WHERE tag_id=$vvv";
                $this->db->query($tag_num_update_sql);
            }
            $sql_values = substr($sql_values, 1);
            $sql .= $sql_values;
            $rs_insert = $this->db->query($sql);
            if (!$rs_insert) {
                return false;
            }
        }

        //进行对比 取差值 进行delete
        $tag_id_delete_array = array_diff($tag_id_old_array, $tag_id_array);
        if ($tag_id_delete_array) {
            $tag_id_delete_string = implode(',', $tag_id_delete_array);
            $sql = "DELETE FROM $this->tags_info_table WHERE article_id = '$article_id' AND tag_id IN($tag_id_delete_string)";
            $rs_delete = $res = $this->db->query($sql);
            if (!$rs_delete) {
                return false;
            }
            //tag表里的tag_num总数记录减一
            $tag_num_delete_sql = "UPDATE $this->tags_table SET tag_usernum = tag_usernum-1 WHERE tag_id IN($tag_id_delete_string)";
            $this->db->query($tag_num_delete_sql);
        }

        //更新文章tag_info
        $rs = $this->getTagsInfoArrayByArticle_id($article_id);
        if ($rs && count($rs) > 0) {
            $tag_info= array();
            foreach ($rs AS $tk => $tv) {
                $tag_info[$tv['tag_id']] = $tv['tag_name'];
            }
            $tag_info = json_encode($tag_info);
            $update_article_tag_sql = "UPDATE $this->article_table SET tag_info = '$tag_info' WHERE article_id=$article_id";
            $this->db->query($update_article_tag_sql);
        }
        return true;
    }

}